// packageMyInfo/pages/device/device.js
import { throttle } from "../../../utils/util"
import { OPEN_DOMAIN } from '../../../utils/config';
const app = getApp()
import { deviceFindAll,deviceDelete,deviceInsert } from "../../../public/api/device.js"
Page({

  /**
   * 页面的初始数据
   */
  data: {
    deviceList: [],
    hideModal: true,
    translations: {},
    uuid: '',
    hideModalDevice: true,
    deviceName: '',
    deviceUuid: '',
    deviceSerial: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) { 

  },

  getDeviceList() {
    let that = this
    let data = {}
    data.uuid = this.data.uuid
    deviceFindAll(data).then(res => {
      if(res.data.code === 1) {
        let currentObj = wx.getStorageSync('currentDevice')
        if(!currentObj && res.data.data.length) {
          currentObj = res.data.data[0]
          wx.setStorageSync('currentDevice', currentObj)
        }
        res.data.data.map(item => {
          item.uuidShow = that.formatString(item.uuid)
          item.current = currentObj.uuid == item.uuid ? true : false
          item.disabled = item.userType == 0 ? false : true
        })
        this.setData({deviceList: res.data.data})
      } else {
        wx.showToast({
          title: res.data.msg,
          icon: 'none'
        })
      }
    })
  },

  formatString(str) {
    if (str.length <= 8) {
      // 如果字符串长度小于或等于8，直接返回原字符串
      return str;
    }
    const start = str.slice(0, 4); // 获取前4位
    const end = str.slice(-4); // 获取后4位
    return `${start}****${end}`; // 用****替换中间部分
  },

  showUuid: throttle(function(e) {
    let uuid = e.currentTarget.dataset.uuid
    wx.showModal({
      title: '',
      content: uuid,
      confirmText: '复制',
      success: (res) => {
        if(res.confirm) {
          wx.setClipboardData({
            data: uuid,
            success: function (res) {
              wx.showToast({
                title: '复制成功',
                icon: 'none'
              });
            }
          });
        }
      }
    })
  },1500),

  doSearch: throttle(function() {
    this.getDeviceList()
  },1500),

  doDelete(e) {
    let that = this
    let uuid = e.currentTarget.dataset.uuid
    wx.showModal({
      title: '删除设备',
      content: '确定要删除该设备吗？',
      success: (res) => {
        if (res.confirm) {
          deviceDelete({uuid}).then(res => {
            if(res.data.code === 1) {
              let currentObj = wx.getStorageSync('currentDevice')
              if(currentObj.uuid == uuid) {
                wx.removeStorageSync('currentDevice')
              }
              wx.showToast({
                title: '删除成功',
                icon: 'success'
              })
              that.getDeviceList()
            } else {
              wx.showToast({
                title: res.data.msg,
                icon: 'none'
              })
            }
          })
        }
      }
    })
  },

  doScan(e) {
    let that = this
    let id = e.currentTarget.dataset.id
    wx.scanCode({
      success(res) {
        console.log(res);
        if (res.result) {
          if(id === 'uuid') {
            if (res.result.length === 32) {
              that.setData({deviceUuid: res.result})
            } else {
              wx.showToast({
                title: '二维码格式错误',
                icon: 'none'
              })
            }
          } else if(id === 'serial') {
            if(res.result.includes("AW") && res.result.length === 9) {
              that.setData({deviceSerial: res.result})
            } else {
              wx.showToast({
                title: '二维码格式错误',
                icon: 'none'
              })
            }
          }
        }
      }
    })
  },

  doBindDevice(e) {
    let type = e.currentTarget.dataset.type
    let state = type == 'handle' ? 1 : 0
    wx.navigateTo({
      url: '../bind/bind?state=' + state
    })
    this.setData({hideModal: true})
  },

  doCancel() {
    this.setData({hideModal: true})
  },

  openDevice() {
    this.setData({hideModalDevice: false})
  },

  doAddDevice() {
    let that = this
    if(this.data.deviceName === '') {
      wx.showToast({
        title: '请输入设备名称',
        icon: 'none'
      })
      return false
    }
    if(this.data.deviceUuid === '' || (this.data.deviceUuid && this.data.deviceUuid.length != 32)) {
      wx.showToast({
        title: '请输入32位的设备SN',
        icon: 'none'
      })
      return false
    }
    // if(this.data.deviceSerial === '') {
    //   wx.showToast({
    //     title: '请输入摄像头SN',
    //     icon: 'none'
    //   })
    //   return false
    // } 
    // else if(!(this.data.deviceSerial.includes("AW") && this.data.deviceSerial.length === 9)) {
    //   wx.showToast({
    //     title: '摄像头SN格式不正确',
    //     icon: 'none'
    //   })
    //   return false
    // }
    this.addByApi()
  },

  addByApi() {
    let data = {}
    let that = this
    data.name = this.data.deviceName
    data.uuid = this.data.deviceUuid
    data.cameraSn = this.data.deviceSerial
    deviceInsert(data).then(res => {
      if(res.data.code === 1) {
        wx.showToast({
          title: '添加成功',
          icon: 'success',
          duration: 1500,
          success() {
            setTimeout(() => {
              that.getDeviceList()
              that.setData({hideModalDevice: true})
            }, 1500)
          }
        })
      } else {
        wx.showToast({
          title: res.data.msg,
          icon: 'none'
        })
      }
    })
  },

  chooseDevice(e) {
    let item = e.currentTarget.dataset.item
    console.log(item);
    wx.setStorageSync('currentDevice', item)
    wx.showToast({
      title: '切换成功',
      icon: 'success',
      duration: 1500,
      success() {
        setTimeout(() => {
          wx.reLaunch({
            url: '/pages/apply/apply'
          })
        }, 1500)
      }
    })
  },

  goPersonSub(e) {
    let { uuid, name, userType } = e.currentTarget.dataset.item
    wx.navigateTo({
      url: '../personSub/personSub?uuid=' + uuid + '&name=' + name + '&userType=' + userType
    })
  },

  doNothing() {
    return false
  },
  
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    const translations = app.globalData.translations;
    this.setData({
      translations
    });
    wx.setNavigationBarTitle({
      title: translations.nav.bind_device
    });
    this.getDeviceList()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})